/**
 * Project: apollo-base-dal
 * 
 * File Created at 2017年2月15日
 * 
 * Copyright 2015-2016 dx.com Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * DongXue software Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with dx.com.
 */
package com.dx.pf.dal.conf;

import java.util.Map;

import org.springframework.beans.PropertyValues;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertyResolver;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.util.Assert;

/** 
* @ClassName: RelaxedPropertyResolver 
* @Description: 从springboot中复制来的参数加载工具
* @author wuzhenfang(wzfbj2008@163.com)
* @date 2017年2月15日 下午2:43:15 
* @version V1.0 
*/
public class RelaxedPropertyResolver implements PropertyResolver{

	private final PropertyResolver resolver;

	private final String prefix;

	public RelaxedPropertyResolver(PropertyResolver resolver) {
		this(resolver, null);
	}

	public RelaxedPropertyResolver(PropertyResolver resolver, String prefix) {
		Assert.notNull(resolver, "PropertyResolver must not be null");
		this.resolver = resolver;
		this.prefix = (prefix == null ? "" : prefix);
	}

	// 获取属性值，找不到抛出异常IllegalStateException
	@Override
	public String getRequiredProperty(String key) throws IllegalStateException {
		return getRequiredProperty(key, String.class);
	}

	// 获取指定类型的属性值，找不到抛出异常IllegalStateException
	@Override
	public <T> T getRequiredProperty(String key, Class<T> targetType) throws IllegalStateException {
		T value = getProperty(key, targetType);
		Assert.state(value != null, String.format("required key [%s] not found", key));
		return value;
	}

	// 获取属性值 如果找不到返回null
	@Override
	public String getProperty(String key) {
		return getProperty(key, String.class, null);
	}

	// 获取属性值，如果找不到返回默认值
	@Override
	public String getProperty(String key, String defaultValue) {
		return getProperty(key, String.class, defaultValue);
	}

	// 获取指定类型的属性值，找不到返回默认值
	@Override
	public <T> T getProperty(String key, Class<T> targetType) {
		return getProperty(key, targetType, null);
	}

	// 获取指定类型的属性值，找不到返回默认值
	@Override
	public <T> T getProperty(String key, Class<T> targetType, T defaultValue) {
		RelaxedNames prefixes = new RelaxedNames(this.prefix);
		RelaxedNames keys = new RelaxedNames(key);
		for (String prefix : prefixes) {
			for (String relaxedKey : keys) {
				if (this.resolver.containsProperty(prefix + relaxedKey)) {
					return this.resolver.getProperty(prefix + relaxedKey, targetType);
				}
			}
		}
		return defaultValue;
	}

	// 获取属性值为某个Class类型，找不到返回null，如果类型不兼容将抛出ConversionException
	public <T> Class<T> getPropertyAsClass(String key, Class<T> targetType) {
		RelaxedNames prefixes = new RelaxedNames(this.prefix);
		RelaxedNames keys = new RelaxedNames(key);
		for (String prefix : prefixes) {
			for (String relaxedKey : keys) {
				if (this.resolver.containsProperty(prefix + relaxedKey)) {
					return ((RelaxedPropertyResolver) this.resolver).getPropertyAsClass(prefix + relaxedKey, targetType);
				}
			}
		}
		return null;
	}

	// 是否包含某个属性
	@Override
	public boolean containsProperty(String key) {
		RelaxedNames prefixes = new RelaxedNames(this.prefix);
		RelaxedNames keys = new RelaxedNames(key);
		for (String prefix : prefixes) {
			for (String relaxedKey : keys) {
				if (this.resolver.containsProperty(prefix + relaxedKey)) {
					return true;
				}
			}
		}
		return false;
	}

	// 替换文本中的占位符（${key}）到属性值，找不到不解析
	@Override
	public String resolvePlaceholders(String text) {
		throw new UnsupportedOperationException("Unable to resolve placeholders with relaxed properties");
	}

	// 替换文本中的占位符（${key}）到属性值，找不到抛出异常IllegalArgumentException
	@Override
	public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException {
		throw new UnsupportedOperationException("Unable to resolve placeholders with relaxed properties");
	}

	/**
	 * Return a Map of all values from all underlying properties that start with the specified key. NOTE: this method can only be used if the underlying resolver is a
	 * {@link ConfigurableEnvironment}.
	 * @param keyPrefix the key prefix used to filter results
	 * @return a map of all sub properties starting with the specified key prefix.
	 * @see PropertySourceUtils#getSubProperties
	 */
	public Map<String, Object> getSubProperties(String keyPrefix) {
		Assert.isInstanceOf(ConfigurableEnvironment.class, this.resolver, "SubProperties not available.");
		ConfigurableEnvironment env = (ConfigurableEnvironment) this.resolver;
		return PropertyFileUtils.getSubProperties(env.getPropertySources(), this.prefix, keyPrefix);
	}

}
